package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.*;
import com.bwie.poi.ExcelUtil;
import com.bwie.pojo.*;
import com.bwie.service.TbOrderService;
import com.bwie.utils.Result;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lenovo
 * @description 针对表【tb_order(订单表)】的数据库操作Service实现
 * @createDate 2025-05-30 09:28:03
 */
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
        implements TbOrderService {

    @Autowired
    HttpServletRequest request;

    @Autowired
    TbProdInfoMapper tbProdInfoMapper;

    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    TbDetailOrderMapper tbDetailOrderMapper;

    @Autowired
    TbProdMapper tbProdMapper;

    @Autowired
    TbImageMapper tbImageMapper;

    @Autowired
    HttpServletResponse response;

    @Autowired
    TbOrderRecordMapper tbOrderRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addOrder(List<TbProdInfo> prodInfoList) {


        //--1 获取用户信息
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error().setMsg("请先登录");
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        String realName = body.get("realName", String.class);

        //--2 判断库存
        BigDecimal amount = new BigDecimal(0.0);
        StringBuilder nameList = new StringBuilder();
        Integer total = 0;
        for (TbProdInfo tbProdInfo : prodInfoList) {
            TbProdInfo prodInfo = tbProdInfoMapper.selectById(tbProdInfo.getInfoId());
            // 检查库存
            if (tbProdInfo.getBuyNum() > prodInfo.getProdStock()) {
                //return Result.error().setMsg("库存不足");
                throw new RuntimeException("库存不足");
            } else {
                // 扣减库存
                prodInfo.setProdStock(prodInfo.getProdStock() - tbProdInfo.getBuyNum());
                tbProdInfoMapper.updateById(prodInfo);
            }

            // 计算订单金额
            amount = prodInfo.getProdPrice().multiply(new BigDecimal(tbProdInfo.getBuyNum())).add(amount);

            // 连接商品名称
            TbProd tbProd = tbProdMapper.selectById(prodInfo.getProdId());
            if (nameList.length() == 0) {
                nameList.append(tbProd.getProdName()).append(prodInfo.getAttrColor());
            } else {
                nameList.append(",").append(tbProd.getProdName()).append(prodInfo.getAttrColor());
            }

            // 计算商品数量
            total += tbProdInfo.getBuyNum();
        }


        //--3 创建订单
        TbOrder tbOrder = new TbOrder();
        tbOrder.setUserId(userId);
        tbOrder.setCreateBy(realName);
        tbOrder.setCreateTime(new Date());

        // 雪花算法生成订单ID
        long orderNo = IdUtil.getSnowflake(1, 1).nextId();
        System.out.println("订单ID：" + orderNo);
        tbOrder.setOrderNo(orderNo);

        tbOrder.setOrderStatus(0);
        tbOrder.setAmount(amount);
        tbOrder.setOrderType(0);
        tbOrder.setCoupon(0);
        tbOrder.setDelivery("");

        // 设置购买商品的名称列表
        tbOrder.setProdInfo(nameList.toString());

        // 设置购买商品的数量
        tbOrder.setProdNum(total);

        tbOrder.setUseScore(0);

        // 保存订单
        tbOrderMapper.insert(tbOrder);


        //--4 创建订单详情
        for (TbProdInfo tbProdInfo : prodInfoList) {
            TbDetailOrder tbDetailOrder = new TbDetailOrder();
            tbDetailOrder.setOrderId(tbOrder.getOrderId());
            tbDetailOrder.setProdId(tbProdInfo.getProdId());
            tbDetailOrder.setProdNum(tbProdInfo.getBuyNum());
            tbDetailOrder.setProdPrice(tbProdInfo.getProdPrice());

            tbDetailOrderMapper.insert(tbDetailOrder);
        }

        // 新增订单记录
        TbOrderRecord tbOrderRecord = new TbOrderRecord();
        tbOrderRecord.setOrderId(tbOrder.getOrderId());

        Integer prodId = prodInfoList.get(0).getProdId();
        tbOrderRecord.setProdId(prodId);

        tbOrderRecord.setRecordContent("用户创建订单");
        tbOrderRecord.setRecordTime(new Date());
        tbOrderRecordMapper.insert(tbOrderRecord);

        return Result.ok();
    }

    @Override
    public Result getOrderList(PageInfoVo pageInfoVo) {

        //--1 构造分页参数
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        //--2 获取订单列表（分页查询）
//        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
//        wrapper.lambda().orderByDesc(TbOrder::getCreateTime);
//        Page<TbOrder> tbOrderPage = tbOrderMapper.selectPage(page, wrapper);
        Page<TbOrder> tbOrderPage = tbOrderMapper.getOrderList(page, pageInfoVo);

        tbOrderPage.getRecords().forEach(tbOrder -> {
            List<TbDetailOrder> tbOrderDetails = tbDetailOrderMapper.selectList(
                    new QueryWrapper<TbDetailOrder>().lambda().eq(TbDetailOrder::getOrderId, tbOrder.getOrderId())
            );

            tbOrderDetails.forEach(tbOrderDetail -> {
                List<TbImage> tbProdImages = tbImageMapper.selectList(
                        new QueryWrapper<TbImage>().lambda().eq(TbImage::getProdId, tbOrderDetail.getProdId())
                );

                // 使用stream流转为图片 列表
                List<String> imageList = tbProdImages.stream().map(item -> item.getImageUrl()).collect(Collectors.toList());

                // 设置 图片列表
                tbOrderDetail.setImageList(imageList);

                tbOrder.setImageList(imageList);
            });

            // 把 订单详情列表 设置到 订单对象中
            tbOrder.setTbDetailOrderList(tbOrderDetails);
        });


        //--3 返回订单列表
        return Result.ok().setData(tbOrderPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result delOrderAll(List<TbOrder> orderList) {

        //判断 订单是否存在
        for (TbOrder tbOrder : orderList) {
            TbOrder order = tbOrderMapper.selectById(tbOrder.getOrderId());
            if (order == null) {
                throw new RuntimeException("订单不存在");
            } else {
                //先删除明细
                tbDetailOrderMapper.delete(
                        new QueryWrapper<TbDetailOrder>().lambda().eq(TbDetailOrder::getOrderId, tbOrder.getOrderId())
                );

                //再删除订单
                tbOrderMapper.deleteById(tbOrder.getOrderId());
            }
        }
        return Result.ok();
    }

    @Override
    public void exportOderExcel(String ids) {

        String[] idsList = ids.split(",");

        ArrayList<Integer> arrayList = new ArrayList<>();

        for (String id : idsList) {
            arrayList.add(Integer.parseInt(id));
        }

        List<TbOrder> tbOrders = tbOrderMapper.selectBatchIds(arrayList);

        ExcelUtil<TbOrder> excelUtil = new ExcelUtil<>(TbOrder.class);

        excelUtil.exportExcel(response, tbOrders, "订单列表");

    }


}




